import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: () => import('@/layout/Index.vue'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/system/User.vue'),
        meta: { title: '用户管理', permission: 'system:user' }
      },
      {
        path: 'role',
        name: 'Role',
        component: () => import('@/views/system/Role.vue'),
        meta: { title: '角色管理', permission: 'system:role' }
      },
      {
        path: 'permission',
        name: 'Permission',
        component: () => import('@/views/system/Permission.vue'),
        meta: { title: '权限管理', permission: 'system:permission' }
      },
      {
        path: 'file',
        name: 'File',
        component: () => import('@/views/file/Index.vue'),
        meta: { title: '文件管理', permission: 'file' }
      },
      {
        path: 'lowcode/designer',
        name: 'LowcodeDesigner',
        component: () => import('@/views/lowcode/PageDesigner.vue'),
        meta: { title: '页面设计器', permission: 'lowcode:designer' }
      },
      {
        path: 'lowcode/list',
        name: 'LowcodeList',
        component: () => import('@/views/lowcode/List.vue'),
        meta: { title: '页面管理', permission: 'lowcode:list' }
      },
      {
        path: 'lowcode/form-designer',
        name: 'FormDesigner',
        component: () => import('@/views/lowcode/FormDesigner.vue'),
        meta: { title: '表单设计器', permission: 'lowcode:form-designer' }
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = store.getters['user/token']
  
  if (to.path === '/login') {
    next()
  } else {
    if (token) {
      // 检查页面权限
      const requiredPermission = to.meta.permission
      if (requiredPermission) {
        const permissions = store.getters['user/permissions']
        if (permissions.includes(requiredPermission)) {
          next()
        } else {
          // 没有权限，跳转到首页或403页面
          next('/home')
          // 或者显示权限不足提示
          // Vue.prototype.$message.error('您没有访问该页面的权限')
        }
      } else {
        // 不需要权限的页面直接访问
        next()
      }
    } else {
      next('/login')
    }
  }
})

export default router
